package com.deepblue.image.maker.config;

import com.deepblue.image.maker.websocket.LocalWebsocketSessionCache;
import com.deepblue.image.maker.websocket.WebSocketHandler;
import com.deepblue.image.maker.websocket.WebsocketHandshakeInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import javax.annotation.Resource;

/**
 * websocket 配置
 *
 * @author yymagicer
 * @version 1.0
 * @date 2021/11/10 上午11:19
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {


    @Resource
    private WebsocketHandshakeInterceptor websocketHandshakeInterceptor;

    @Resource
    private LocalWebsocketSessionCache localWebsocketSessionCache;


    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry
                //添加myHandler消息处理对象，和websocket访问地址
                .addHandler(webSocketHandler(), "/ws")
                //设置允许跨域访问
                .setAllowedOrigins("*")
                //添加拦截器可实现用户链接前进行权限校验等操作
                .addInterceptors(websocketHandshakeInterceptor);
    }

    @Bean
    public WebSocketHandler webSocketHandler(){
        return new WebSocketHandler(localWebsocketSessionCache);
    }
}
